

import os
from dexen.system.base.individual import Individual
from dexen.system.base.spec import DexenSpec


DIR_SIZE = 1000
ARCH_DIR_NAME = "ARCHIVE"
INDS_DIR_NAME = "INDS"
SLAVES_DIR_NAME = "SLAVES"

class ArchiveMgr(object):
    def __init__(self, spec):
        assert isinstance(spec, DexenSpec)
        topdir = os.path.dirname(os.path.abspath(__file__))
        self.arch_dir = os.path.join(topdir, ARCH_DIR_NAME)
        self.my_arch_dir = os.path.join(self.arch_dir, spec.mastername)
        self.inds_dir = os.path.join(self.my_arch_dir, INDS_DIR_NAME)
        self.slaves_dir = os.path.join(self.my_arch_dir, SLAVES_DIR_NAME)
        self._create_dirs()
        self.spec = spec

    def _create_dirs(self):
        self._create_dir(self.arch_dir)
        self._create_dir(self.my_arch_dir)
        self._create_dir(self.inds_dir)
        self._create_dir(self.slaves_dir)
            
    def _create_dir(self, dirpath):
        if not os.path.exists(dirpath):
            os.mkdir(dirpath)
    
    def _get_dir_name(self, id):
        base = ((id-1) / DIR_SIZE) * DIR_SIZE + 1
        ceiling = base + DIR_SIZE - 1
        name = str(base) + "_" + str(ceiling)
        return name
    
    def archive_data(self, ind):
        assert isinstance(ind, Individual)
        prev_dir = os.getcwd()
        os.chdir(self.inds_dir)
        dirname = self._get_dir_name(ind.__id__)
        #print "dirname", dirname
        if not os.path.exists(dirname):
            os.mkdir(dirname)
        os.chdir(dirname)
        
        ind_dirname = str(ind.__id__)
        if not os.path.exists(ind_dirname):
            os.mkdir(ind_dirname)
        os.chdir(ind_dirname)
        
        files = ind.get_archived_data()
        for name, content in files.items():
            f = open(name, "w")
            f.write(content)
            f.close()
        os.chdir(prev_dir)
        
    def archive_console_output(self, slave_name, output):
        outfile = os.path.join(self.slaves_dir, slave_name)
        f = open(outfile, "a")
        f.write(output)
        f.close()        

    def get_slaves_dir(self):
        return self.slaves_dir
    

#===============================================================================
# TESTING
#===============================================================================
def test():
    spec = DexenSpec("HAHA")
    spec.mastername = "DANAAAAAAAAAA"
    arc_mgr = ArchiveMgr(spec)
    ind = Individual()
    ind.__id__ = 1560
    ind.archive_data("ali.txt", range(25))
    ind.archive_data("veli.txt", "Nasilsin koc hahahahahaha")
    arc_mgr.archive_data(ind)
    
    
def main():
    test()

if __name__ == "__main__":
    main()

     